package com.bsoft.gol.hcs.specialist.service.impl;

import com.bsoft.gol.hcs.clinical.bean.req.GetTreatmentItemRequest;
import com.bsoft.gol.hcs.clinical.bean.req.QueryDrugInformationRequest;
import com.bsoft.gol.hcs.clinical.bean.vo.TreatmentItemTypeList;
import com.bsoft.gol.hcs.clinical.service.TreatmentApplicationService;
import com.google.common.collect.Lists;
import ctd.account.UserRoleToken;
import ctd.controller.exception.ControllerException;
import ctd.dictionary.DictionaryItem;
import ctd.dictionary.controller.DictionaryController;
import ctd.persistence.annotation.DAOTransaction;
import ctd.spring.boot.annotation.SsdevReference;
import ctd.spring.boot.annotation.SsdevService;
import ctd.util.KeyGenerator;
import ctd.util.annotation.RpcService;
import com.bsoft.gol.hcs.enumcase.OperationTypeEnum;
import hcn.base.BaseCopywriterConfig;
import hcn.base.Dept;
import hcn.base.Organization;
import hcn.base.operate.qo.QueryOperativeListQo;
import hcn.bean.UserAllVo;
import hcn.rep.request.DiseaseSpeciesSimpleListReq;
import hcn.rep.response.DiseaseSpeciesSimpleListRep;
import hcn.specialist.DiseaseSpecies;
import com.bsoft.gol.hcs.his.bean.historydrug.DrugList;
import com.bsoft.gol.hcs.his.bean.historydrug.QueryDrugResp;
import com.bsoft.gol.hcs.his.service.IElectronicMedicalHisService;
import com.bsoft.gol.hcs.his.service.IIndexHisService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.atag.util.bbp.RoleUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import pcn.service.web.BaseDeviceService;
import pcn.vo.consultation.DeptAndDoctorVo;
import service.rpc.IBaseCopywriterConfigRpcService;
import service.rpc.IDeptMainRpcService;
import service.rpc.IOrganizationRpcService;
import com.bsoft.gol.hcs.specialist.bean.request.*;
import com.bsoft.gol.hcs.specialist.bean.response.*;
import com.bsoft.gol.hcs.specialist.bean.vo.DiseaseVO;
import com.bsoft.gol.hcs.specialist.dao.*;
import com.bsoft.gol.hcs.specialist.entity.*;
import com.bsoft.gol.hcs.specialist.service.IDiseaseSpeciesService;
import com.bsoft.gol.hcs.utils.CommonUtils;
import com.bsoft.gol.hcs.utils.Constants;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author tongtp
 * @version v0.1
 * @className DiseaseSpeciesService
 * @description 病种管理
 * @create 2020-07-14 10:33
 **/
@SsdevService("diseaseSpecies")
public class DiseaseSpeciesServiceImpl implements IDiseaseSpeciesService {
    private static final Logger log = LoggerFactory.getLogger(CrucialIndexImpl.class);

    @Autowired
    FusCrucialIndexRecordDAO fusCrucialIndexRecordDAO;

    @Autowired
    DiseaseSpeciesDAO diseaseSpeciesDAO;
    @Autowired
    DiseaseSpeciesRelateDAO diseaseSpeciesRelateDAO;
    @Autowired
    DiseasePeriodDAO diseasePeriodDAO;
    @Autowired
    DiseaseExtendPropertyDAO diseaseExtendPropertyDAO;
    @Autowired
    DiseaseCollectConfigDAO diseaseCollectConfigDAO;
    @Autowired
    FusAnswerCheckReportInfoDAO fusAnswerCheckReportInfoDAO;
    @Autowired
    FollowUpRecordsDAO followUpRecordsDAO;
    @Autowired
    FusIndexResultDAO fusIndexResultDAO;
    @Autowired
    GroupRecordExtendPropertyDAO groupRecordExtendPropertyDAO;
    @Autowired
    GroupRecordStagesPropertyDAO groupRecordStagesPropertyDAO;
    @Autowired
    IIndexHisService indexHisService;
    @Autowired
    private IElectronicMedicalHisService electronicMedicalHisService;
    @Autowired
    private TreatmentApplicationService treatmentApplicationService;
    @Autowired
    private DiseaseDeptDAO DiseaseDeptDAO;
    @Autowired
    private IDeptMainRpcService deptMainRpcService;
    @Autowired
    private IOrganizationRpcService organizationRpcService;
    @SsdevReference("hcn.baseDeviceService")
    private BaseDeviceService baseDeviceService;
    @Autowired
    private IBaseCopywriterConfigRpcService baseCopywriterConfigService;

    @Autowired
    private FusDiseaseProtocolDAO fusDiseaseProtocolDAO;

    @Override
    public List<DiseaseSpecies> queryAllChronicDiseaseList() {
        List<DiseaseSpecies> diseaseSpeciesList = new ArrayList<>();
        //1.获取当前登录用户的角色信息
        String commonRole = RoleUtils.getCurrentCommonRole();
        if (CommonUtils.isEmpty(commonRole)) {
            diseaseSpeciesList = diseaseSpeciesDAO.queryAllChronicDiseaseList();
        } else {
            //2.获取当前登录用户信息
            UserAllVo allByOnline = baseDeviceService.getAllByOnline();
            //3.判断当前用户是医生还是管理员
            if ("admin".equals(commonRole)) {
                if (CommonUtils.isEmpty(allByOnline.getOrgId())) {//租户管理员，返回全部
                    diseaseSpeciesList = diseaseSpeciesDAO.queryAllChronicDiseaseList();
                } else {
                    diseaseSpeciesList = diseaseSpeciesDAO.queryChronicDiseaseListByOrg(allByOnline.getLocalOrgId());
                }
            } else if ("doctor".equals(commonRole)) {
                //租户管理员，返回全部
                if (CommonUtils.isEmpty(allByOnline.getLocalDeptId())) {
                    diseaseSpeciesList = diseaseSpeciesDAO.queryAllChronicDiseaseList();
                } else {
                    diseaseSpeciesList = diseaseSpeciesDAO.queryChronicDiseaseListByOrg(allByOnline.getLocalOrgId());
                }
            } else {
                diseaseSpeciesList = diseaseSpeciesDAO.queryAllChronicDiseaseList();
            }
        }
        return diseaseSpeciesList;
    }

    /**
     * 获取病种基础信息列表，科室不可以为空
     **/
    @Override
    @RpcService
    public List<DiseaseSpecies> queryChronicDiseaseList(QueryDiseaseSpeciesListReq docTeamListReq) throws ControllerException {
        List<DiseaseSpecies> chronicDiseaseList = diseaseSpeciesDAO.queryChronicDiseaseList(docTeamListReq.getDepartmentId());
        if (CollectionUtils.isNotEmpty(chronicDiseaseList)) {
            return chronicDiseaseList;
        } else {
            return new ArrayList<>();
        }
    }

    @Override
    public List<DiseaseSpeciesSimpleListRep> querySimpleDiseaseList(DiseaseSpeciesSimpleListReq req) {
        List<DiseaseSpecies> chronicDiseaseList = diseaseSpeciesDAO.queryChronicDiseaseListByOrg(req.getOrganizationId());
        if (CollectionUtils.isNotEmpty(chronicDiseaseList)) {
            return chronicDiseaseList.stream().map(d -> {
                DiseaseSpeciesSimpleListRep rep = new DiseaseSpeciesSimpleListRep();
                BeanUtils.copyProperties(d, rep);
                return rep;
            }).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }


    @Override
    @RpcService
    public List<QueryDiseaseTypeResponse> queryAllDiseaseSpeciesList() {
        List<QueryDiseaseTypeResponse> queryDiseaseTypeResponse = new ArrayList<>();
        //1.分页获取病种基础信息
        List<DiseaseSpecies> chronicDiseaseList = diseaseSpeciesDAO.queryAllDiseaseTypeList();
        if (CollectionUtils.isEmpty(chronicDiseaseList)) {
            return null;
        }
        for (DiseaseSpecies record : chronicDiseaseList) {
            QueryDiseaseTypeResponse response = new QueryDiseaseTypeResponse();
            BeanUtils.copyProperties(record, response);
            //获取数据采集配置
            List<DiseaseCollectConfigEntity> collectConfigList = diseaseCollectConfigDAO.queryDiseaseCollectConfigByDiseaseTypeId(record.getDiseaseTypeId());
            response.setCollectConfigList(collectConfigList);
            queryDiseaseTypeResponse.add(response);
        }
        return queryDiseaseTypeResponse;
    }


    @Override
    @RpcService
    public DiseaseTypeListResponse queryDiseaseSpeciesListByPage(QueryDiseaseSpeciesListReq docTeamListReq) {
        List<QueryDiseaseTypeResponse> queryDiseaseTypeResponse = new ArrayList<>();
        //1.分页获取病种基础信息
        List<DiseaseSpecies> chronicDiseaseList = diseaseSpeciesDAO.queryDiseaseSpeciesList(docTeamListReq);
        Long total = diseaseSpeciesDAO.queryDiseaseSpeciesCount(docTeamListReq);
        DiseaseTypeListResponse responsel = new DiseaseTypeListResponse();
        if (CollectionUtils.isNotEmpty(chronicDiseaseList)) {
            for (DiseaseSpecies record : chronicDiseaseList) {
                QueryDiseaseTypeResponse response = new QueryDiseaseTypeResponse();
                BeanUtils.copyProperties(record, response);
                //2.获取病种分期
                DiseasePeriodEntity diseasePeriod = new DiseasePeriodEntity();
                diseasePeriod.setDiseaseTypeId(record.getDiseaseTypeId());
                List<DiseasePeriodResponse> diseasePeriodList = this.queryDiseasePeriodList(diseasePeriod);
                response.setDiseasePeriodList(diseasePeriodList);
                //3.获取病种基础属性。关联类型，1关联疾病、2关联并发症、3关联手术、4关联指标、5关联操作、6关联用药
                List<DiseaseSpeciesRelate> results = diseaseSpeciesRelateDAO.queryDiseaseSpeciesRelateList(record.getDiseaseTypeId(), "1");
                response.setDiseaseSpeciesRelateList(results);

                List<DiseaseSpeciesRelate> comresults = diseaseSpeciesRelateDAO.queryDiseaseSpeciesRelateList(record.getDiseaseTypeId(), "2");
                response.setCompliceList(comresults);

                List<DiseaseSpeciesRelate> optresults = diseaseSpeciesRelateDAO.queryDiseaseSpeciesRelateList(record.getDiseaseTypeId(), "3");
                response.setOperativeList(optresults);

                List<DiseaseSpeciesRelate> indresults = diseaseSpeciesRelateDAO.queryDiseaseSpeciesRelateList(record.getDiseaseTypeId(), "4");
                if (CommonUtils.isNotEmpty(indresults)) {
                    List<DiseaseSpeciesRelate> collect = indresults.stream().map(index -> {
                        FusCrucialIndexRecord fusCrucialIndexRecord = fusCrucialIndexRecordDAO.get(index.getRelateRecordId());
                        if (CommonUtils.isNotEmpty(fusCrucialIndexRecord)) {
                            index.setIndexType(fusCrucialIndexRecord.getIndexType());
                            index.setIndexClassifyId(fusCrucialIndexRecord.getIndexClassifyId());
                        }
                        return index;
                    }).collect(Collectors.toList());
                    response.setIndexList(collect);
                } else {
                    response.setIndexList(indresults);
                }


                List<DiseaseSpeciesRelate> operateList = diseaseSpeciesRelateDAO.queryDiseaseSpeciesRelateList(record.getDiseaseTypeId(), "5");
                response.setOperateList(operateList);

                List<DiseaseSpeciesRelate> drugList = diseaseSpeciesRelateDAO.queryDiseaseSpeciesRelateList(record.getDiseaseTypeId(), "6");
                response.setDurgList(drugList);
                //4.获取病种扩展属性
                List<DiseaseExtendPropertyResponse> extendPropertyResponseList = this.queryExtendPropertyResponseListByDiseaseId(record.getDiseaseTypeId());
                response.setExtendPropertyList(extendPropertyResponseList);
                //5.获取数据采集配置
                List<DiseaseCollectConfigEntity> collectConfigList = diseaseCollectConfigDAO.queryDiseaseCollectConfigByDiseaseTypeId(record.getDiseaseTypeId());
                response.setCollectConfigList(collectConfigList);

                queryDiseaseTypeResponse.add(response);
            }
            responsel.setList(queryDiseaseTypeResponse);
            responsel.setTotal(total);
        }else{
            responsel.setTotal(0L);
            responsel.setList(new ArrayList<>());
        }
        return responsel;
    }

    /**
     * 根据关联类型和病种id获取相关信息
     * 获取病种基础属性。关联类型，1关联疾病、2关联并发症、3关联手术、4关联指标、5关联操作、6关联用药
     *
     * @param relateReq
     * @return
     * @throws ControllerException
     */
    @Override
    public List<DiseaseSpeciesRelate> queryDiseaseSpeciesRelateListByType(QueryDiseaseRelateListReq relateReq) throws ControllerException {
        if (CommonUtils.isEmpty(relateReq.getDiseaseId())) {
            throw new ControllerException("病种id不可为空");
        }
        if (CommonUtils.isEmpty(relateReq.getType())) {
            throw new ControllerException("关联类型不可为空");
        }
        List<DiseaseSpeciesRelate> diseaseSpeciesRelates = diseaseSpeciesRelateDAO.queryDiseaseSpeciesRelateList(relateReq.getDiseaseId(), relateReq.getType());
        return diseaseSpeciesRelates;
    }

    /**
     * 查询病种扩展属性
     *
     * @param diseaseId 入参
     * @return response
     **/
    @Override
    public List<DiseaseExtendPropertyResponse> queryExtendPropertyResponseListByDiseaseId(Long diseaseId) {
        List<DiseaseExtendPropertyResponse> extendPropertyResponseList = Lists.newArrayList();
        List<DiseaseExtendPropertyEntity> firstExtendPropertyList = diseaseExtendPropertyDAO.queryFirstDiseaseByDiseaseTypeId(diseaseId);
        if (CommonUtils.isNotEmpty(firstExtendPropertyList)) {
            for (DiseaseExtendPropertyEntity firstExtendProperty : firstExtendPropertyList) {
                DiseaseExtendPropertyResponse extendPropertyResponse = new DiseaseExtendPropertyResponse();
                BeanUtils.copyProperties(firstExtendProperty, extendPropertyResponse);
                //获取子集扩展属性
                List<DiseaseExtendPropertyEntity> sonExtendPropertyList = diseaseExtendPropertyDAO.querySecondDiseaseByDiseaseTypeId(diseaseId, firstExtendProperty.getExtendId());
                extendPropertyResponse.setDiseaseList(sonExtendPropertyList);
                extendPropertyResponseList.add(extendPropertyResponse);
            }
        }
        return extendPropertyResponseList;
    }

    /**
     * 保存病种配置
     *
     * @param request 入参
     * @return response
     **/
    @Override
    @RpcService
    @DAOTransaction
    public DiseaseVO saveDiseaseSpecies(DiseaseTypeReq request) throws ControllerException {
        if (request == null) {
            throw new ControllerException("参数不能为空");
        }
        if (StringUtils.isAnyEmpty(request.getOrganizationId(), request.getDepartmentId(), request.getDepartmentName()
                , request.getDiseaseTypeName(), request.getPinyinCode())) {
            throw new ControllerException("必填项不能为空");
        }

        //增加
        if (request.getOperateType().equals(OperationTypeEnum.ADD.getCode().toString())) {
            //1.根据科室和病种名称查询病种是否存在
            List<DiseaseSpecies> recordinfo = diseaseSpeciesDAO.queryDiseaseTypeByName(request.getDepartmentId(), request.getDiseaseTypeName());
            if (CommonUtils.isNotEmpty(recordinfo)) {
                throw new ControllerException("该名称已经存在");
            }
            //2.保存基础属性
            DiseaseSpecies record = new DiseaseSpecies();
            BeanUtils.copyProperties(request, record);
            record.setGmtCreate(new Timestamp(System.currentTimeMillis()));
            if (StringUtils.isEmpty(request.getPeriodViewDispFlag())) {
                request.setPeriodViewDispFlag(Constants.ZORE_STRING);
            }
            diseaseSpeciesDAO.save(record);
            request.setDiseaseTypeId(record.getDiseaseTypeId());
        } else {
            //更新
            if (CommonUtils.isNotEmpty(request.getDiseaseTypeId())) {
                QueryExecutionListRequest req = new QueryExecutionListRequest();
                req.setDiseaseTypeId(request.getDiseaseTypeId());
                //1.更新病种基础信息
                DiseaseSpecies record = diseaseSpeciesDAO.getDiseaseTypeDetail(request.getDiseaseTypeId());
                if (record == null) {
                    throw new ControllerException("该病种存在");
                }
                record.setDiseaseTypeName(request.getDiseaseTypeName());
                record.setDepartmentCode(request.getDepartmentCode());
                record.setDepartmentId(request.getDepartmentId());
                record.setDepartmentName(request.getDepartmentName());
                record.setOrganizationId(request.getOrganizationId());
                record.setPinyinCode(request.getPinyinCode());
                record.setAbbreviation(request.getAbbreviation());
                record.setStatus(request.getStatus());
                record.setPeriodViewDispFlag(request.getPeriodViewDispFlag());
                diseaseSpeciesDAO.update(record);

                //2.1删除所有关联基础属性
                diseaseSpeciesRelateDAO.deleteDiseaseSpeciesRelateId(request.getDiseaseTypeId());
            } else {
                throw new ControllerException("病种id不能为空");
            }
        }
        //2.2保存基础属性
        this.saveDiseaseSpeciesRelate(request);
        //3.扩展属性保存或更新
        List<DiseaseExtendPropertyResponse> extendPropertyList = request.getExtendPropertyList();
        if (CommonUtils.isNotEmpty(extendPropertyList)) {
            //1.删除病种对应所有配置
            diseaseExtendPropertyDAO.deleteDiseaseExtendPropertyByDiseaseTypeId(request.getDiseaseTypeId());
            for (DiseaseExtendPropertyResponse extendProperty : extendPropertyList) {
                //2.保存
                this.saveDiseaseExtendProperty(extendProperty, request.getDiseaseTypeId());
            }
        }
        //4.数据采集保存或更新
        List<DiseaseCollectConfigEntity> collectConfigList = request.getCollectConfigList();
        if (CommonUtils.isNotEmpty(collectConfigList)) {
            //1.删除病种对应所有配置
            diseaseCollectConfigDAO.deleteByDiseaseTypeId(request.getDiseaseTypeId());
            //2.保存传入数据
            for (DiseaseCollectConfigEntity collectConfig : collectConfigList) {
                this.saveDiseaseCollectConfig(collectConfig, request.getDiseaseTypeId());
            }
        }
        //保存病种协议
        if (CommonUtils.isNotEmpty(request.getProtocolEntity())){
            if (request.getProtocolEntity().getDiseaseTypeId()==null || request.getProtocolEntity().getDiseaseTypeId()<=0){
                request.getProtocolEntity().setDiseaseTypeId(request.getDiseaseTypeId());
            }
            saveDiseaseProtocol(request.getProtocolEntity());
        }
        DiseaseVO diseaseVO = new DiseaseVO();
        diseaseVO.setDiseaseId(request.getDiseaseTypeId());
        diseaseVO.setDiseaseName(request.getDiseaseTypeName());
        return diseaseVO;
    }

    /**
     * 保存病种分期
     *
     * @param diseasePeriod 分期
     **/
    @Override
    @RpcService
    public void saveDiseasePeriod(DiseasePeriodEntity diseasePeriod) {
        if (StringUtils.isEmpty(diseasePeriod.getStatus())) {
            diseasePeriod.setStatus(String.valueOf(Constants.ZORE));
        }
        if (CommonUtils.isNull(diseasePeriod.getPeriodId())) {
            diseasePeriod.setCreateTime(new Timestamp(System.currentTimeMillis()));
            diseasePeriodDAO.save(diseasePeriod);
        } else {
            diseasePeriodDAO.update(diseasePeriod);
        }
    }

    /**
     * 根据病种查询科室
     **/
    @Override
    @RpcService
    public List<DiseaseSpecies> queryDiseaseDept(DiseaseSpecies request) {
        List<DiseaseSpecies> dept = DiseaseDeptDAO.queryDiseaseDepartmentName(request.getDiseaseTypeId());
        return dept;
    }

    /**
     * 根据机构和病种查询标准科室
     */
    @RpcService
    @Override
    public DeptAndDoctorVo.deptBean queryDiseaseStandardDept(Long diseaseTypeId) throws ControllerException {

        DiseaseSpecies diseaseSpecies = DiseaseDeptDAO.get(diseaseTypeId);
        if (CommonUtils.isEmpty(diseaseSpecies)) {
            return null;
        }
        String organizationId = diseaseSpecies.getOrganizationId();
        Organization organization = organizationRpcService.getOrgDetailByOrgCode(organizationId);
        if (CommonUtils.isEmpty(organization)) {
            return null;
        }
        Dept deptMain = deptMainRpcService.getDeptByLocalDeptId(organization.getOrgId(), diseaseSpecies.getDepartmentId());
        if (CommonUtils.isEmpty(deptMain)) {
            return null;
        }
        String standardDeptId = deptMain.getStandardDeptId();
        if (CommonUtils.isEmpty(standardDeptId)) {
            return null;
        }
        //获取标准科室名称
        DictionaryItem dictionaryItem = DictionaryController.instance().get("sys.org.hedomain").getItem(standardDeptId);
        if (CommonUtils.isEmpty(dictionaryItem)) {
            return null;
        }
        DeptAndDoctorVo.deptBean dept = new DeptAndDoctorVo.deptBean();

        dept.setConsultDeptName(dictionaryItem.getText());
        dept.setStandardDeptId(dictionaryItem.getKey());
        return dept;
    }


    /**
     * 保存病种基础属性
     *
     * @param request 入参
     **/
    private void saveDiseaseSpeciesRelate(DiseaseTypeReq request) {
        //1保存诊断属性
        if (CommonUtils.isNotEmpty(request.getDiseaseSpeciesRelateList())) {
            for (DiseaseSpeciesRelate diseaseSpeciesRelate : request.getDiseaseSpeciesRelateList()) {
                if (StringUtils.isAnyEmpty(diseaseSpeciesRelate.getRelateRecordId(), diseaseSpeciesRelate.getRelateName())) {
                    continue;
                }
                diseaseSpeciesRelate.setDiseaseTypeId(request.getDiseaseTypeId());
                diseaseSpeciesRelate.setDiseaseTypeName(request.getDiseaseTypeName());
                diseaseSpeciesRelate.setRelateType("1");
                diseaseSpeciesRelate.setGmtCreate(new Timestamp(System.currentTimeMillis()));
                diseaseSpeciesRelateDAO.save(diseaseSpeciesRelate);
            }
        }
        //2保存并发症属性
        if (CommonUtils.isNotEmpty(request.getCompliceList())) {
            for (DiseaseSpeciesRelate complice : request.getCompliceList()) {
                if (StringUtils.isAnyEmpty(complice.getRelateRecordId(), complice.getRelateName())) {
                    continue;
                }
                complice.setDiseaseTypeId(request.getDiseaseTypeId());
                complice.setDiseaseTypeName(request.getDiseaseTypeName());
                complice.setRelateType("2");
                complice.setGmtCreate(new Timestamp(System.currentTimeMillis()));
                diseaseSpeciesRelateDAO.save(complice);
            }
        }
        //3保存手术属性
        if (CommonUtils.isNotEmpty(request.getOperativeList())) {
            for (DiseaseSpeciesRelate operative : request.getOperativeList()) {
                if (StringUtils.isAnyEmpty(operative.getRelateRecordId(), operative.getRelateName())) {
                    continue;
                }
                operative.setDiseaseTypeId(request.getDiseaseTypeId());
                operative.setDiseaseTypeName(request.getDiseaseTypeName());
                operative.setRelateType("3");
                operative.setGmtCreate(new Timestamp(System.currentTimeMillis()));
                diseaseSpeciesRelateDAO.save(operative);
            }
        }
        //4保存指标属性
        if (CommonUtils.isNotEmpty(request.getIndexList())) {
            for (DiseaseSpeciesRelate indexResult : request.getIndexList()) {
                if (StringUtils.isAnyEmpty(indexResult.getRelateRecordId(), indexResult.getRelateName())) {
                    continue;
                }
                indexResult.setDiseaseTypeId(request.getDiseaseTypeId());
                indexResult.setDiseaseTypeName(request.getDiseaseTypeName());
                indexResult.setRelateType("4");
                indexResult.setGmtCreate(new Timestamp(System.currentTimeMillis()));
                diseaseSpeciesRelateDAO.save(indexResult);
            }
        }
        //5保存操作属性
        if (CommonUtils.isNotEmpty(request.getOperateList())) {
            for (DiseaseSpeciesRelate operateResult : request.getOperateList()) {
                if (StringUtils.isAnyEmpty(operateResult.getRelateRecordId(), operateResult.getRelateName())) {
                    continue;
                }
                operateResult.setDiseaseTypeId(request.getDiseaseTypeId());
                operateResult.setDiseaseTypeName(request.getDiseaseTypeName());
                operateResult.setRelateType("5");
                operateResult.setGmtCreate(new Timestamp(System.currentTimeMillis()));
                diseaseSpeciesRelateDAO.save(operateResult);
            }
        }
        //6保存用药属性
        if (CommonUtils.isNotEmpty(request.getDurgList())) {
            for (DiseaseSpeciesRelate durgResult : request.getDurgList()) {
                if (StringUtils.isAnyEmpty(durgResult.getRelateRecordId(), durgResult.getRelateName())) {
                    continue;
                }
                durgResult.setDiseaseTypeId(request.getDiseaseTypeId());
                durgResult.setDiseaseTypeName(request.getDiseaseTypeName());
                durgResult.setRelateType("6");
                durgResult.setGmtCreate(new Timestamp(System.currentTimeMillis()));
                diseaseSpeciesRelateDAO.save(durgResult);
            }
        }
    }

    /**
     * 保存病种扩展属性
     *
     * @param extendProperty 扩展属性
     **/
    private void saveDiseaseExtendProperty(DiseaseExtendPropertyResponse extendProperty, Long diseaseTypeId) {
        DiseaseExtendPropertyEntity extendPropertyEntity = new DiseaseExtendPropertyEntity();
        BeanUtils.copyProperties(extendProperty, extendPropertyEntity);
        this.saveDiseaseExtendPropertyEntity(extendPropertyEntity, diseaseTypeId);

        //属性子集保存
        if (CommonUtils.isNotEmpty(extendProperty.getDiseaseList())) {
            for (DiseaseExtendPropertyEntity sonExtendPropertyEntity : extendProperty.getDiseaseList()) {
                sonExtendPropertyEntity.setParentId(extendPropertyEntity.getExtendId());
                this.saveDiseaseExtendPropertyEntity(sonExtendPropertyEntity, diseaseTypeId);
            }
        }
    }

    /**
     * 保存病种扩展属性
     *
     * @param diseaseExtendPropertyEntity 扩展属性
     * @param diseaseTypeId               病种id
     **/
    private void saveDiseaseExtendPropertyEntity(DiseaseExtendPropertyEntity diseaseExtendPropertyEntity, Long diseaseTypeId) {
        diseaseExtendPropertyEntity.setDiseaseTypeId(diseaseTypeId);
        diseaseExtendPropertyEntity.setCreateTime(new Timestamp(System.currentTimeMillis()));
        if (StringUtils.isEmpty(diseaseExtendPropertyEntity.getOptGroupFlag())) {
            diseaseExtendPropertyEntity.setOptGroupFlag(String.valueOf(Constants.ZORE));
        }
        if (StringUtils.isEmpty(diseaseExtendPropertyEntity.getViewDispFlag())) {
            diseaseExtendPropertyEntity.setViewDispFlag(String.valueOf(Constants.ZORE));
        }
        diseaseExtendPropertyDAO.save(diseaseExtendPropertyEntity);
    }

    /**
     * 保存数据采集配置
     *
     * @param collectConfig 扩展属性
     **/
    private void saveDiseaseCollectConfig(DiseaseCollectConfigEntity collectConfig, Long diseaseTypeId) {
        collectConfig.setDiseaseTypeId(diseaseTypeId);
        collectConfig.setCreateTime(new Timestamp(System.currentTimeMillis()));
        diseaseCollectConfigDAO.save(collectConfig);


    }


    /**
     * 根据病种id查询病种分期
     *
     * @param diseasePeriod 分期
     * @return 病种内所有分期
     */
    @Override
    @RpcService
    public List<DiseasePeriodResponse> queryDiseasePeriodList(DiseasePeriodEntity diseasePeriod) {
        List<DiseasePeriodResponse> PeriodResponseList = Lists.newArrayList();
        //1.根据病种id查询一级分期
        List<DiseasePeriodEntity> diseasePeriodList = diseasePeriodDAO.queryOneLevelListByDiseaseTypeId(diseasePeriod.getDiseaseTypeId());
        if (CommonUtils.isEmpty(diseasePeriodList)) {
            return PeriodResponseList;
        }
        //2.循环获取子集数据
        for (DiseasePeriodEntity periodEntity : diseasePeriodList) {
            DiseasePeriodResponse diseasePeriodResponse = new DiseasePeriodResponse();
            BeanUtils.copyProperties(periodEntity, diseasePeriodResponse);
            this.queryPeriodByParentId(diseasePeriodResponse);
            PeriodResponseList.add(diseasePeriodResponse);
        }
        return PeriodResponseList;
    }


    /**
     * 根据父级分期id查询所有子级分期
     *
     * @param periodResponse 父级分期
     * @return 所有子分期
     */
    private void queryPeriodByParentId(DiseasePeriodResponse periodResponse) {
        List<DiseasePeriodEntity> diseasePeriodList = diseasePeriodDAO.querySonListByParentPeriodId(periodResponse.getPeriodId());
        if (CommonUtils.isEmpty(diseasePeriodList)) {
            return;
        }
        List<DiseasePeriodResponse> periodResponseList = Lists.newArrayList();
        periodResponse.setDiseasePeriod(periodResponseList);
        for (DiseasePeriodEntity diseasePeriodEntity : diseasePeriodList) {
            DiseasePeriodResponse diseasePeriod = new DiseasePeriodResponse();
            BeanUtils.copyProperties(diseasePeriodEntity, diseasePeriod);
            periodResponseList.add(diseasePeriod);
            this.queryPeriodByParentId(diseasePeriod);
        }
    }

    /**
     * @Description: 删除病种信息
     * @Author: 李文龙
     * @Date: 2020/7/20 14:17
     **/
    @Override
    @RpcService
    @DAOTransaction
    public void deleteDiseaseSpecies(QueryDiseaseTypeListReq request) throws ControllerException {
        log.info("FlowInvestigationService deleteDiseaseSpecies 进入 {}", request.toString());
        if (CommonUtils.isEmpty(request.getDiseaseTypeId())) {
            throw new ControllerException("病种id不能为空");
        }
        if ("3".equals(request.getOperateType().toString())) {
            DiseaseSpecies record = diseaseSpeciesDAO.getDiseaseTypeDetail(request.getDiseaseTypeId());
            if (CommonUtils.isEmpty(record)) {
                throw new ControllerException("没有病种id相关的记录");
            }
            //查询指标是否使用
            Long count = followUpRecordsDAO.getCountByDiseaseTypeId(request.getDiseaseTypeId());
            //指标未被使用删除（）
            if (count == null || count < 1L) {
                //删除病种分期
                diseasePeriodDAO.deleteDiseasePeriodByDiseaseTypeId(request.getDiseaseTypeId());
                //删除病种扩展属性
                diseaseExtendPropertyDAO.deleteDiseaseExtendPropertyByDiseaseTypeId(request.getDiseaseTypeId());
                //删除病种基本属性
                diseaseSpeciesRelateDAO.deleteDiseaseSpeciesRelateId(request.getDiseaseTypeId());
                //删除病种采集信息
                diseaseCollectConfigDAO.deleteByDiseaseTypeId(request.getDiseaseTypeId());
                //删除病种基本信息
                diseaseSpeciesDAO.deleteBydiseaseTypeId(request.getDiseaseTypeId());
            } else {
                //指标在使用删除（）
                throw new ControllerException("该病种信息已经在使用中");
            }
        } else {
            //启用 operateType	String	1	Y	操作类型，0停用 1启用  3删除
            diseaseSpeciesDAO.updateById(request.getDiseaseTypeId(), request.getOperateType());
        }
    }

    /**
     * @Description: 获取关联疾病(诊断)、并发症、手术、操作、用药等信息
     * @Author: liwenlong
     * @Date: 2020/7/20 14:17
     **/
    @Override
    @RpcService
    public List<OperativeListResp> queryOperativeList(QueryOperativeListQo request) throws ControllerException {
        List<OperativeListResp> operativeListRespList = Lists.newArrayList();
        if ("5".equals(request.getType())) {
            //5.查询操作
            GetTreatmentItemRequest treatmentItemRequest = new GetTreatmentItemRequest();
            treatmentItemRequest.setVisitOrganization(request.getOrganizationId());
            treatmentItemRequest.setInputCode(request.getPyCode());
            List<TreatmentItemTypeList> treatmentItemTypeList = treatmentApplicationService.getTreatmentItem(treatmentItemRequest);
            if (CommonUtils.isEmpty(treatmentItemRequest)) {
                return operativeListRespList;
            }
            for (TreatmentItemTypeList treatmentItem : treatmentItemTypeList) {
                OperativeListResp operativeListResp = new OperativeListResp();
                operativeListResp.setRelateRecordId(treatmentItem.getTreatmentItemCode());
                operativeListResp.setRelateName(treatmentItem.getTreatmentItemName());
                operativeListRespList.add(operativeListResp);
            }
            return operativeListRespList;
        } else if ("6".equals(request.getType())) {
            //6.查询用药
            QueryDrugInformationRequest drugRequest = new QueryDrugInformationRequest();
            drugRequest.setHospitalCode(request.getOrganizationId());
            drugRequest.setKeyWord(request.getPyCode());
            drugRequest.setDrugType(request.getDrugType());
            drugRequest.setPageNo(Constants.ONE);
            drugRequest.setPageSize(Constants.TEN);
            QueryDrugResp response = electronicMedicalHisService.queryDrugInfoByCode(drugRequest);
            if (response == null || CommonUtils.isEmpty(response.getDrugLists()) || CommonUtils.isEmpty(response.getDrugLists().getDrugList())) {
                return operativeListRespList;
            }
            for (DrugList drugList : response.getDrugLists().getDrugList()) {
                OperativeListResp operativeListResp = new OperativeListResp();
                operativeListResp.setRelateRecordId(drugList.getDrugsNumber());
                operativeListResp.setRelateName(drugList.getDrugName());
                operativeListResp.setDrugSpecifications(drugList.getDrugSpecifications());
                operativeListResp.setDrugProductionPlace(drugList.getDrugProductionPlace());
                operativeListRespList.add(operativeListResp);
            }
            return operativeListRespList;

        } else {
            operativeListRespList = indexHisService.queryOperativeList(request).getData();
        }
        return operativeListRespList;
    }


    /**
     * @Description: 获取患者详情中关联指标类型
     * @Author: liwenlong
     * @Date: 2020/7/20 14:17
     **/
    @Override
    @RpcService
    public List<PatientIndexTypeResp> queryPatientIndexType(QueryOperativeListRequest request) throws ControllerException {
        try {
            if (!StringUtils.isNoneEmpty(request.getPageNo() + "", request.getPageSize() + "")) {
                throw new ControllerException("分页参数不可为空");
            }
            return diseaseSpeciesRelateDAO.queryIndexTypeByDiseaseTypeId(request);
        } catch (Exception e) {
            log.info("获取患者详情中关联指标类型失败", e.getMessage());
            throw new ControllerException("获取患者详情中关联指标类型失败");
        }
    }

    /**
     * @Description: 获取患者详情中关联指标数据列表
     * @Author: liwenlong
     * @Date: 2020/7/20 14:17
     **/
    @Override
    @RpcService
    public List<PatientIndexListResp> queryPatientIndexList(QueryOperativeListRequest request) throws ControllerException {
        if (StringUtils.isAnyEmpty(request.getPageNo() + "", request.getPageSize() + "")) {
            throw new ControllerException("分页参数不可为空");
        }
        if (CommonUtils.isEmpty(request.getPatientId())) {
            throw new ControllerException("患者标识不可为空");
        }
        if (CommonUtils.isEmpty(request.getItemId())) {
            throw new ControllerException("项目id不可为空");
        }

        try {
            return fusAnswerCheckReportInfoDAO.queryIndexListByPatientId(request);
        } catch (Exception e) {
            log.info("获取关联指标数据列表失败", e.getMessage());
            throw new ControllerException("获取关联指标数据列表失败");
        }
    }

    /**
     * 根据病种分期id删除病种分期
     *
     * @param diseasePeriod 分期信息
     **/
    @Override
    @RpcService
    @DAOTransaction
    public void deleteDiseasePeriod(DiseasePeriodEntity diseasePeriod) throws ControllerException {
        //1.判断是否使用分期，否则删除
        Long count = groupRecordStagesPropertyDAO.getCountGroupRecordStagesByStagesId(diseasePeriod.getDiseaseTypeId(), diseasePeriod.getPeriodId());
        if (count > Constants.ZORE) {
            throw new ControllerException("该分期在使用中，无法删除");
        }
        //2.删除子节点
        this.deleteSonDiseasePeriods(diseasePeriod.getDiseaseTypeId(), diseasePeriod.getPeriodId());
        //3.删除对应节点
        diseasePeriodDAO.deleteDiseasePeriodByPeriodId(diseasePeriod.getPeriodId());
    }

    /**
     * 根据病种分期id删除所有子节点病种分期
     *
     * @param parentPeriodId 父级分期id
     */
    public void deleteSonDiseasePeriods(Long diseaseTypeId, Long parentPeriodId) throws ControllerException {
        //查询子节点
        List<DiseasePeriodEntity> diseasePeriodList = diseasePeriodDAO.querySonListByParentPeriodId(parentPeriodId);
        if (CommonUtils.isEmpty(diseasePeriodList)) {
            return;
        }
        //需要删除得分期id集合
        List<Long> periodIdList = Lists.newArrayList();
        for (DiseasePeriodEntity periodEntity : diseasePeriodList) {
            Long count = groupRecordStagesPropertyDAO.getCountGroupRecordStagesByStagesId(diseaseTypeId, periodEntity.getPeriodId());
            if (count > Constants.ZORE) {
                throw new ControllerException("该分期在使用中，无法删除");
            }
            periodIdList.add(periodEntity.getPeriodId());
        }

        //删除传入的分期id和子节点所有分期数据
        diseasePeriodDAO.deleteDiseasePeriodByPeriodIds(periodIdList);
        for (DiseasePeriodEntity periodEntity : diseasePeriodList) {
            this.deleteSonDiseasePeriods(periodEntity.getDiseaseTypeId(), periodEntity.getPeriodId());
        }
    }

    /**
     * 根据病种扩展属性id删除病种扩展属性
     *
     * @param diseaseExtendProperty 扩展属性信息
     **/
    @Override
    @RpcService
    public void deleteExtendProperty(DiseaseExtendPropertyEntity diseaseExtendProperty) throws ControllerException {
        List<Long> extendIdList = Lists.newArrayList();
        //根据扩展属性id获取所有子集属性。
        extendIdList = diseaseExtendPropertyDAO.queryExtendIdByParentId(diseaseExtendProperty.getExtendId());
        extendIdList.add(diseaseExtendProperty.getExtendId());
        //判断入组记录是否使用扩展属性
        Long count = groupRecordExtendPropertyDAO.getCountGroupRecordExtendPropertyByExtendId(diseaseExtendProperty.getDiseaseTypeId(), extendIdList);
        //未使用可以删除
        if (CommonUtils.isNull(count)) {
            diseaseExtendPropertyDAO.deleteDiseaseExtendPropertyById(extendIdList);
        } else {
            throw new ControllerException("该扩展属性正在使用中");
        }
    }
    /**
     * 根据病种id获取入组协议
     **/
    @Override
    public FusDiseaseProtocolEntity getDiseaseProtocol(FusDiseaseProtocolEntity request) throws ControllerException {
        String tenantId = UserRoleToken.getCurrent().getTenantId();
        if (CommonUtils.isEmpty(request.getDiseaseTypeId())) {
            throw new ControllerException("病种id不能为空！");
        }
        FusDiseaseProtocolEntity entity = fusDiseaseProtocolDAO.getFusDiseaseProtocolByDiseaseId(request.getDiseaseTypeId());
        if (CommonUtils.isEmpty(entity)){
            entity = new FusDiseaseProtocolEntity();
            //该病种还没配置时取文案配置初始值
            BaseCopywriterConfig copywriterConfigByCopywriterCode = baseCopywriterConfigService.getCopywriterConfigByCopywriterCode("0131-01", tenantId);
            if (CommonUtils.isNotEmpty(copywriterConfigByCopywriterCode)){
                entity.setDiseaseTypeId(request.getDiseaseTypeId());
                entity.setContent(copywriterConfigByCopywriterCode.getContent());
            }
        }
        return entity;
    }

    /**
     * 病种入组协议  --重置返回文案配置初始内容
     **/
    @Override
    public FusDiseaseProtocolEntity resetDiseaseProtocol(FusDiseaseProtocolEntity request) throws ControllerException {
        String tenantId = UserRoleToken.getCurrent().getTenantId();
        FusDiseaseProtocolEntity entity = new FusDiseaseProtocolEntity();
        //该病种还没配置时取文案配置初始值
        BaseCopywriterConfig copywriterConfig = baseCopywriterConfigService.getCopywriterConfigByCopywriterCode("0131-01", tenantId);
        if (CommonUtils.isEmpty(copywriterConfig)){
            throw  new ControllerException("文案配置-入组协议查询为空！");
        }
        entity.setContent(copywriterConfig.getContent());
        return entity;
    }
    /**
     * 病种入组协议  --保存
     **/
    @Override
    public FusDiseaseProtocolEntity saveDiseaseProtocol(FusDiseaseProtocolEntity request){

        FusDiseaseProtocolEntity entity = fusDiseaseProtocolDAO.getFusDiseaseProtocolByDiseaseId(request.getDiseaseTypeId());
        if (CommonUtils.isEmpty(entity)){
            //新增
            request.setDiseaseProtocolId(KeyGenerator.randomGenerate());
            fusDiseaseProtocolDAO.save(request);
        }else{
            //更新
            entity.setContent(request.getContent());
            fusDiseaseProtocolDAO.update(entity);
        }
        return request;
    }


}
